package org.TheSubject;

/**
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 *
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
//采用双指针的方式
public class Solution19OfHot {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy=head;
        ListNode firstNode=head;
        ListNode secondNode=firstNode;
        ListNode startNode=head;
        int i=1;
        while (secondNode.next!=null){
            if (i<n){
                break;
            }
            secondNode=secondNode.next;i++;
        }
        while (secondNode.next!=null){
            secondNode=secondNode.next;
            startNode=firstNode;
            firstNode=firstNode.next;
        }
        if (firstNode==dummy){
            dummy=dummy.next;
            firstNode.next=null;
        }else {
            startNode.next=firstNode.next;
            firstNode.next=null;
        }
        return dummy;
    }
    private static class ListNode{
        int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
